<!-- 费用审核 项目内的费用审核 -->
<template>
  <div v-if="$auth('PROJECT.PROJECT_FEE_REVIEW')">
    <a-card :bordered="false">
      <a-descriptions :title="$t('all.autotext469')"></a-descriptions>
      <s-table
        ref="table"
        size="default"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 'max-content', y: 500 }"
        class="clear-padding"
      >
        <template slot="title">
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item :label="$t('all.autotext1156')">
                    <a-input
                      v-model="queryParam.applyNo"
                      :placeholder="$t('all.autotext1371')"
                    />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item :label="$t('all.autotext1236')">
                    <a-select
                      v-model="queryParam.type"
                      :placeholder="$t('all.autotext1348')"
                      default-value="0"
                      allowClear
                    >
                      <a-select-option
                        v-for="item in $const.SUBJECTANDREESA"
                        :key="item.value"
                        :value="item.value"
                      >
                        {{ item.desc }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <template v-if="advanced">
                  <a-col :md="8" :sm="24">
                    <a-form-item :label="$t('all.autotext1521')">
                      <a-input
                        v-model="queryParam.createrUserNo"
                        :placeholder="$t('all.autotext1371')"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-model-item
                      :label="$t('all.autotext758')"
                      labelAlign="left"
                    >
                      <a-range-picker
                        @change="handleSelectDate"
                        v-model="queryDate"
                        allowClear
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="8" :sm="24" v-if="queryParam.type">
                    <a-form-item :label="$t('all.autotext1251')">
                      <a-input
                        v-model="queryParam.userNo"
                        :placeholder="$t('all.autotext1371')"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col class="noshrink" :md="8" :sm="24">
                    <a-form-item :label="$t('all.autotext949')">
                      <a-select
                        v-model="queryParam.orgId"
                        allowClear
                        :placeholder="$t('all.autotext1348')"
                        option-filter-prop="children"
                        show-search
                        filter
                      >
                        <a-select-option
                          v-for="item in allCenterList"
                          :key="item.id"
                          :value="item.id"
                        >
                          {{ `${item.researchCenterNo} - ${item.orgName}` }}
                        </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :md="8" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    :style="
                      (advanced && { float: 'right', overflow: 'hidden' }) || {}
                    "
                  >
                    <a-button type="primary" @click="searchTable">{{
                      $t('all.autotext30')
                    }}</a-button>
                    <a-button style="margin-left: 8px" @click="reset">{{
                      $t('all.autotext340')
                    }}</a-button>
                    <a-button
                      style="margin-left: 8px"
                      :loading="exporting"
                      icon="export"
                      @click="clickExport"
                      v-if="$auth('FEE_REVIEW.FEE_REVIEW_EXPORT')"
                      >{{ $t('all.autotext1014') }}</a-button
                    >

                    <a @click="toggleAdvanced" style="margin-left: 8px">
                      {{
                        advanced
                          ? $t('all.autotext760.1')
                          : $t('all.autotext760.2')
                      }}
                      <a-icon :type="advanced ? 'up' : 'down'" />
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          
          <!-- tab 切换 start -->
          <a-tabs @change="handleTab">
              <a-tab-pane v-for="(list, i) in tabs" :key="i" :tab="list.desc"></a-tab-pane>
          </a-tabs>
          <!-- tab 切换  end -->
        </template>
        <template slot="status" slot-scope="text, record">
          {{ record.status | enumValueByKey($const.EXAMINE_TYPE) }}
        </template>
        <template slot="createTime" slot-scope="text">
          <span v-if="text">{{ text | moment }}</span>
        </template>
        <template slot="ptsNo" slot-scope="text, record">
          {{
            record.type == $const.SUBJECTANDREESA.DAISHENGPI.value
              ? record.researchDetailNo
              : text
          }}
        </template>
        <template slot="type" slot-scope="text, record">
          {{ record.type | enumValueByKey($const.SUBJECTANDREESA) }}
        </template>
        <template slot="applyReason" slot-scope="text">
          <span class="textover" :title="text">{{ text }}</span>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a
            @click="clickView(record)"
            v-if="$auth('FEE_REVIEW.FEE_REVIEW_DETAIL')"
            >{{ $t('all.autotext568') }}</a
          >
        </template>
      </s-table>
      <DetailView
        :type="1"
        @closeCallback="closeCallback"
        @openPopup="openPopup"
        @payRecord="payRecord"
        @refresh="refreshTable"
        ref="detailView"
        :visible="visible"
        :costId="costId"
      />
      <AuditFailure
        :visible="visibles"
        @uploadModalCancel="visibles = false"
        @uploadClickConfirm="uploadClickConfirm"
        :auditStatus="auditStatus"
        ref="AuditFailure"
      />
      <Approve
        v-model="oveVisibles"
        :applyNo="applyNo"
        :oldStatus="oldStatus"
        :auditStatus="auditStatus"
        @ok="approveOk"
        ref="Approve"
      />
    </a-card>
  </div>
</template>
<script>
import {
  processListAudit,
  switchAudit,
  getCostExport,
  costRecordPay,
  preCheckForFinanceAudit
} from '@/api/cost/audit'
import DetailView from '@/views/cost-auditing/detail.vue'
import AuditFailure from '@/views/cost-auditing/components/auditFailure'
import Approve from '@/views/cost-auditing/components/approve'
import {
  FINANCE_STATUS,
  APPLIER_STATUS,
  PROJECT_ADMIN
} from '@/constants/common'
import { buildPaginationObj } from '@/components/Table'
import { exportExcel } from '@/utils/util'
import { columns } from './config'
import { apiGetAllCenter } from '@api/cost/cost'

export default {
  components: {
    DetailView,
    AuditFailure,
    Approve
  },
  computed: {
    tabs() {
      if (this.$store.getters.role.code === 'SYS_FINANCE') {
        return FINANCE_STATUS
      }
      if (this.$store.getters.role.code === 'PROJECT_ADMIN') {
        return PROJECT_ADMIN
      }
      return APPLIER_STATUS
    }
  },
  data() {
    return {
      // tab切换
      tabsKey: null,
      visible: false,
      visibles: false,
      oveVisibles: false,
      detailInfo: {},
      queryParam: {
        proId: localStorage.getItem('CURRENT_PROID'),
        orgId: ''
      },
      costId: 0,
      applyNo: '',
      oldStatus: '',
      queryDate: [],
      loadData: (parameter) => {
        if (this.$auth('FEE_REVIEW.FEE_REVIEW_LIST')) {
          if (this.$route.query.id) {
            const userNoParams = {}
            if (this.queryParam.userNo) {
              if (
                this.queryParam.type ===
                this.$const.SUBJECTANDREESA.DAISHENGPI.value
              ) {
                userNoParams.researchDetailNo = this.queryParam.userNo
              } else {
                userNoParams.ptsNo = this.queryParam.userNo
              }
            }
            this.queryParam.proId = this.$route.query.id
            return processListAudit(
              Object.assign(
                { status: this.tabsKey },
                parameter,
                this.queryParam,
                userNoParams
              )
            )
              .then((res) => {
                this.pageSize = res.totalCount
                return res
              })
              .catch(() => {})
          }
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      advanced: false,
      thisStatus: '',
      columns,
      pageSize: null,
      auditStatus: {}, // 审核弹窗审核状态
      exporting: false,
      allCenterList: []
    }
  },
  mounted() {
    this.approvalCost()
    this.getAllCenterList()
  },
  created() {
    this.tabsKey = this.tabs[0].value
    // 设置项目id
    const pro = localStorage.getItem('CURRENT_PROID')
    if (pro) {
      this.$route.query.id = parseInt(pro)
    }

    // 如果是从首页看板来的，要弹出详情（处理弹框）
    if (this.$route.query.from === 'high') {
      this.tabsKey = this.tabs[1].value
      console.log('costId', this.$route.query.costId)
      this.clickView({ id: Number(this.$route.query.costId) })
    }
  },
  methods: {
    approveOk() {
      this.visibles = false
      this.visible = false
      this.$refs.table.refresh()
    },
    // 用于切换tab状态的
    handleTab(key) {
      this.approvalCost()
      this.tabsKey = this.tabs[key].value
      this.queryParam = {
        proId: this.$route.query.id
      }
      this.queryDate = []
      this.$refs.table.refresh(true)
    },
    // 点击展开 详细搜索信息
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    // 点击重置
    reset() {
      this.queryParam = {
        proId: this.$route.query.id,
        orgId: ''
      }
      this.queryDate = []
      this.$refs.table.refresh(true)
    },
    // 点击查看
    clickView(record) {
      this.costId = record.id
      this.applyNo = record.applyNo
      this.oldStatus = record.status
      this.thisStatus = record.status
      setTimeout(() => {
        this.visible = true
      })
      this.clickViewPoint()
    },
    // 处理发起日期选择框改变时产生的回调
    handleSelectDate(date, dateString) {
      this.queryDate = date
      this.queryParam.applyStartTime = dateString[0]
      this.queryParam.applyEndTime = dateString[1]
    },
    // 点击查询
    searchTable() {
      this.$refs.table.refresh(true)
    },
    // 点击查询
    refreshTable() {
      this.$refs.table.refresh()
    },
    // 弹窗关闭回调
    closeCallback() {
      this.visible = false
    },
    // 审核弹窗关闭回调
    uploadModalCancel() {
      this.visibles = false
      this.oveVisibles = false
    },
    // 审核弹窗确认回调
    uploadClickConfirm(value) {
      const status = value.status === true ? 1 : -1
      if (status === 1) {
        this.clickAgree() // 费用审核点击同意埋点
      } else {
        this.clickReject() // 费用审核点击驳回埋点
      }
      this.$refs.AuditFailure.confirmLoading = true
      switchAudit({
        id: value.id,
        status: status,
        applyNo: this.applyNo,
        oldStatus: this.oldStatus,
        refuseReason: value.refuseReason,
        comment: value.comment,
        auditArray: value.auditArray.length
          ? JSON.stringify(value.auditArray)
          : undefined
      })
        .then((res) => {
          this.$refs.AuditFailure.confirmLoading = false
          this.$refs.AuditFailure.form = {}
          this.$message.success(this.$t('all.autotext470'))
          this.closeCallback()
          this.uploadModalCancel()
          this.$refs.table.refresh()
          // 中央事件总线 通知研究者/受试者费用申请列表及时刷新
          this.$globalVue.$emit('approvalCostUpdate')
        })
        .catch(() => {
          this.$refs.AuditFailure.confirmLoading = false
        })
    },
    // 打开审核弹窗
    async openPopup(value) {
      if (value.status === 1) {
        this.auditStatus = value
        this.oveVisibles = true
        return
      }
      if (
        value.status === true &&
        this.$store.getters.roles[0]?.code === 'SYS_FINANCE'
      ) {
        const check = await preCheckForFinanceAudit({ feeApplyId: value.id })
        if (check.flag) {
          const that = this
          this.$confirm({
            title: this.$t('all.autotext730'),
            content: (h) => {
              return h(
                'div',
                check.message.map((node) => h('p', node))
              )
            },
            onOk() {
              that.auditStatus = value
              that.visibles = true
            }
          })
        } else {
          this.auditStatus = value
          this.visibles = true
        }
        return
      }
      this.auditStatus = value
      this.visibles = true
    },
    clickExport() {
      const params = { ...this.queryParam, status: this.tabsKey }
      if (this.queryParam.userNo) {
        if (
          this.queryParam.type === this.$const.SUBJECTANDREESA.DAISHENGPI.value
        ) {
          params.researchDetailNo = this.queryParam.userNo
        } else {
          params.ptsNo = this.queryParam.userNo
        }
      }
      this.exporting = true
      // params.pageSize = this.pageSize
      getCostExport(params)
        .then((res) => {
          this.exporting = false
          exportExcel(this.$t('all.autotext469'), res)
        })
        .catch((_) => {
          this.exporting = false
        })
    },
    // 获取所有中心下拉列表
    getAllCenterList() {
      apiGetAllCenter({ proId: this.$route.query.id }).then((res) => {
        this.allCenterList = res
      })
    },
    // 费用审核页面浏览埋点
    approvalCost() {},
    // 点击查看埋点
    clickViewPoint() {},
    // 费用审核点击同意埋点
    clickAgree() {},
    // 费用审核点击驳回埋点
    clickReject() {},
    // 费用审核点击个税办理埋点
    payRecord() {
      this.$refs.detailView.payLoading = true
      costRecordPay({ id: this.costId, applyNo: this.applyNo })
        .then((res) => {
          this.$refs.detailView.payLoading = false
          this.$message.success(this.$t('all.autotext470'))
          this.closeCallback()
          this.uploadModalCancel()
          this.$refs.table.refresh()
        })
        .catch((_) => {
          this.$refs.detailView.payLoading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.textover {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
